<?php

namespace app\api\controller\admin;

use app\common\controller\TApi;
use app\common\library\Sms;
use think\Db;
use think\Validate;

/**
 * 老师接口
 */
class Admin extends TApi
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'wechatSign', 'wechatAuth', 'wechatBing'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    private function login_result() {
        $admininfo = $this->auth->getAdmininfo();

        $admininfo['deptname'] = Db::name('dts_dept')->where('id', $admininfo['dept_id'])->value('name');
        
        $arrIds = explode(',', $admininfo['position_ids']);
        $arrData = Db::name('dts_config_position')->where('id', 'in', $arrIds)->select();
        $admininfo['positionArr'] = array_column((array)$arrData, 'name');

        $num = Db::name('dts_approve_usecar')->where(['enter_driver_id' => $admininfo['id'], 'status' => 4])->count(1);
        if($num) {
            $admininfo['isDriver'] = true;
        }else {
            $num = Db::name('dts_approve_refuel')->where(['enter_driver_id' => $admininfo['id'], 'status' => 1])->count(1);
            $admininfo['isDriver'] = $num != 0 ? true : false;
        }
        $admininfo['flag'] = 2;
        $admininfo['classes'] = $this->auth->getClassInfo();
        $admininfo['ruleList'] = $this->auth->getRuleList();

        return $admininfo;
    }

    //我的班级
    public function myClass() {
        
        $list = $this->auth->getClassInfo();

        $this->success('success', $list);
    }

    /**
     * 会员登录
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $this->success(__('Logged in successful'), $this->login_result());
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $admin = \app\admin\model\Admin::get(['mobile' => $$mobile]);
        if (!$admin) {
            $this->error('手机号错误');
        }

        if ($admin->status != 'normal') {
            $this->error(__('Account is locked'));
        }
        //如果已经有账号则直接登录
        $ret = $this->auth->direct($admin->id);

        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $this->success(__('Logged in successful'), $this->login_result());
        } else {
            $this->error($this->auth->getError());
        }
    }

    //微信签名
    public function wechatSign() {

        $url = $this->request->get('url');
        if(!$url) {
            $this->error("授权签名url有误");
        }
        $weChat = new \app\api\library\WeChat;
        $weChat->getApp()->jssdk->setUrl($url);
        $signPackage = $weChat->getApp()->jssdk->buildConfig(['scanQRCode'], $debug = false, $beta = false, $json = false);
        
        $this->success('成功', $signPackage);
    }

    //微信授权登录
    public function wechatAuth() {

        $code = $this->request->get('code');
        if(!$code) {
            $this->error("微信授权信息有误");
        }
        $weChat = new \app\api\library\WeChat;
        try{
            $wechatUser = $weChat->getOauth()->user();
        }catch(\Exception $e) {
            $this->error('授权登录失败');
        }
        $admin = \app\admin\model\Admin::where('open_id', $wechatUser['id'])->find();
        if(!$admin) {
            $wechatUser['iswechat'] = 0;
            $this->success('未授权登录', $wechatUser);
        }
        
        $this->auth->direct($admin['id']);
        $data = $this->login_result();
        $data['iswechat'] = 1;
        $this->success('授权登录成功', $data);
    }

    //绑定微信
    public function wechatBing() {

        $account = $this->request->post('account');
        $password = $this->request->post('password');
        $openid = $this->request->post('openid');
        $nickName = $this->request->post('nickName');
        $headimgurl = $this->request->post('headimgurl');
        if (!$account || !$password || !$openid) {
            $this->error('请输入账号密码');
        }
        $ret = $this->auth->login($account, $password);
        if(!$ret) {
            $this->error($this->auth->getError());
        }

        $admin = $this->auth->getAdmininfo();
        \app\admin\model\Admin::where('id', $admin['id'])->update(['open_id' => $openid, 'open_avatar' => $headimgurl, 'open_nickname' => $nickName]);

        $this->success('授权登录成功', $this->login_result());
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 重置密码
     * @ApiMethod (POST)
     * @param string $password    旧密码
     * @param string $newpassword 新密码
     * @param string $confirm     确认密码
     */
    public function resetpwd()
    {
        $password = $this->request->post("password");
        $newpassword = $this->request->post("newpassword");
        $confirm = $this->request->post("confirm");

        if (!$password || !$newpassword || !$confirm) {
            $this->error(__('Invalid parameters'));
        }
        //验证密码
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if($newpassword != $confirm) {
            $this->error('二次输入密码不一致');
        }

        $ret = $this->auth->changepwd($newpassword, $password);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    //设置头像
    public function setAvatar() {
        
        $avatar = $this->request->post("avatar");

        if (!$avatar) {
            $this->error('请上传头像');
        }

        $admin = $this->auth->getAdmininfo();

        \app\admin\model\Admin::where('id', $admin['id'])->update(['avatar' => $avatar]);

        $this->success('success');
    }

    //更新用户信息
    public function refresh() {

        $info = $this->login_result();

        $this->success('success', $info);
    }
}